<script lang="ts">
  import type { Group as GroupType } from '$lib/Database/SB/groups.js';
  import type { Event as EventType } from '$lib/Database/SB/events.js';
  import Message from '$lib/Loading/Message.svelte';
  import root from '$lib/Utility/root';
  import { onMount } from 'svelte';
  import Group from '$lib/Events/Group.svelte';
  import Event from '$lib/Events/Event.svelte';

  export let data;

  let groupsResponse: Promise<Response>;

  onMount(async () => {
    groupsResponse = fetch(root(`/api/events/group?slug=${data.group}`));
  });

  const asGroup = (group: any) => group as GroupType;

  const asEvent = (event: any) => event as EventType;
</script>

{#await groupsResponse}
  <Message message="Loading group ..." />
{:then group}
  {#if group}
    {#await group.json()}
      <Message message="Parsing group ..." />
    {:then json}
      {#if json === null}
        <Message message="" loader="ripple" slot>
          This group may not exist. Please
          <a href={'#'} on:click={() => location.reload()}>try again</a> later.
        </Message>
      {:else}
        {@const group = asGroup(json)}

        <Group {group} />

        <p />

        <details open>
          <summary>Events</summary>

          {#await fetch(root(`/api/events?group=${data.group}`))}
            <Message message="Loading events ..." />
          {:then eventsResponse}
            {#await eventsResponse.json()}
              <Message message="Parsing events ..." />
            {:then events}
              {#if events}
                {#each events as rawEvent, i}
                  <Event event={asEvent(rawEvent)} />

                  {#if i < events.length - 1}
                    <p />
                  {/if}
                {/each}
              {/if}
            {:catch}
              <Message message="" loader="ripple" slot withReload>Error parsing events.</Message>
            {/await}
          {/await}
        </details>
      {/if}
    {:catch}
      <Message message="" loader="ripple" slot withReload>Error parsing group.</Message>
    {/await}
  {:else}
    <Message message="Parsing groups ..." />
  {/if}
{:catch}
  <Message message="" loader="ripple" slot withReload>Error loading group.</Message>
{/await}
